package rise.message;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Logout extends Packet {
	
	String username;
	
	private static final String USERNAME_ATTRIBUTE = "username";
	
	public Logout(String username, int port, double lat, double lon) {
		super(PacketType.LOGOUT, port, lat, lon);
		this.username = username;
	}

	@Override
	public String toXML() {
		Document doc = null;
		try {
			doc = super.createXMLDocument();
		} catch (ParserConfigurationException e1) {
			e1.printStackTrace();
		}
		
	    Element root = doc.createElement(rootElementTag());
	    doc.appendChild(root);
	    root.setAttribute(USERNAME_ATTRIBUTE, username);
	    
	    Element connectionElement = super.createConnectionElement(doc);
	    root.appendChild(connectionElement);
	    
	    String result = null;
	    try {
			result = super.generateString(doc);
		} catch (TransformerFactoryConfigurationError  e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return result;
	}

	@Override
	String rootElementTag() {
		return PacketType.LOGOUT.toString();
	}
	
	public static Logout createLogout(String xmlString){
		Document doc = Packet.createXMLDocumentFromString(xmlString);

		NodeList list = doc.getElementsByTagName(PacketType.LOGOUT.toString());
		Node rootNode = list.item(0);
		Node connectionNode = rootNode.getFirstChild();

		NamedNodeMap rootAttributes = rootNode.getAttributes();
		NamedNodeMap connectionAttributes = connectionNode.getAttributes();
		
		return new Logout(
				rootAttributes.getNamedItem(USERNAME_ATTRIBUTE).getNodeValue(),
				Integer.parseInt(connectionAttributes.getNamedItem(Packet.PORT_ATTRIBUTE).getNodeValue()),
				Double.parseDouble(connectionAttributes.getNamedItem(Packet.LAT_ATTRIBUTE).getNodeValue()),
				Double.parseDouble(connectionAttributes.getNamedItem(Packet.LON_ATTRIBUTE).getNodeValue())
				);
	}

	public String getUsername() {
		return username;
	}

	@Override
	public String getReceiver() {
		return this.getUsername();
	}
}
